条件语句 if 和 switch

go中可以在if中写操作,然后在进行判断,switch 后面可以不跟上表达式,switch 中的 case 后面自动会加上 break,除非使用 fallthrough

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main

import (
"fmt"
"io/ioutil"
)

func func1(){
const filename = "aaa.txt"
// 读取文件内容,返回两个值,第一个是内容,另一个是错误信息
contents, err := ioutil.ReadFile(filename)
if err!=nil{
fmt.Println(err)
}else{
fmt.Printf("%s\n", contents)
}
fmt.Println(contents)
}

func func2 (){
const filename = "aaa.txt"
// 或者将读取文件和 if 写在同一行
if contents, err := ioutil.ReadFile(filename); err!=nil{
fmt.Println(err)
}else{
fmt.Printf("%s\n", contents)
}
// 此处会出错,因为变量 contents 是在 if 中定义的,作用域为 if 以内
// fmt.Println(contents)
}

func grade( score int) string {
// go 中 switch 会自动 break,除非使用 fallthrough
// switch 后面可以不跟表达式,直接写在 case 后面即可
g := ""
switch {
case score<0 || score > 100:
panic(fmt.Sprintf("Wrong score: %d", score)) // panic 表示异常,终止程序继续往下运行
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score < 100:
g = "A"
}
return g
}

func main(){
func1()
func2()

fmt.Println(
grade(0),
grade(10),
grade(60),
grade(70),
grade(80),
grade(90),
grade(100),
grade(101),
)
}

fallthrough 穿透

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import "fmt"

func main() {
number := 100
switch {
case number > 10:
fmt.Println("> 10")
fallthrough // 穿透下一层级。会打印 '> 10' 和 '>20'
case number > 20:
fmt.Println("> 20")
case number > 30:
fmt.Println("> 30")
}
}

switch 结合 type 判断类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import "fmt"

func main() {
// 定义一个 interface
var number interface{}
// 给 number 赋值
number = 3.1415926
// 根据值判断出类型,然后结合 switch
switch number.(type) {
case float32:
fmt.Println("float32")
case float64:
fmt.Println("float64") // float64 会被输出
default:
fmt.Println("unknow")
}
}

goto